package com.zjb.demo.framework.web.service;

import cn.hutool.core.util.StrUtil;
import com.zjb.demo.common.config.AppConfig;
import com.zjb.demo.common.constant.CacheConstants;
import com.zjb.demo.common.constant.UserConstants;
import com.zjb.demo.common.domain.request.RegisterBody;
import com.zjb.demo.common.exception.ServiceException;
import com.zjb.demo.common.util.SecurityUtils;
import com.zjb.demo.framework.manager.AsyncManager;
import com.zjb.demo.system.domain.User;
import com.zjb.demo.system.service.SysConfigService;
import com.zjb.demo.system.service.UserService;
import org.noear.redisx.plus.RedisBucket;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

/**
 * @author 庄佳彬
 * @since 2023/12/31 00:31
 */
@Component
public class RegisterService {
    @Inject
    private UserService userService;

    @Inject
    private SysConfigService configService;

    @Inject
    private AppConfig appConfig;

    @Inject
    private RedisBucket redisBucket;

    @Inject
    private AsyncManager asyncManager;

    public String register(RegisterBody registerBody) {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        var sysUser = new User();
        sysUser.setUserName(username);

        // 验证码开关
        boolean captchaEnabled = appConfig.getCaptchaEnabled();
        if (captchaEnabled) {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if (StrUtil.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StrUtil.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (userService.checkUserNameUnique(sysUser)) {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        } else {
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            if (userService.registerUser(sysUser)) {
                asyncManager.saveLoginInfo(username, "Register", "注册成功");
            } else {
                msg = "注册失败,请联系系统管理人员";
            }
        }
        return msg;
    }

    /**
     * 验证验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisBucket.get(verifyKey);
        redisBucket.remove(verifyKey);
        if (captcha == null) {
            throw new ServiceException("验证码错误");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new ServiceException("验证码错误");
        }
    }

}
